<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { getApi } from '@/api/tenant/data-source-info';
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';

  const props = defineProps({
    currentId: {
      type: String,
      default: () => null,
    },
  });

  const formSchema = reactive<FormSchema[]>([
    { field: 'id', hidden: true },
    {
      field: 'name',
      label: '名称',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'host',
      label: '地址',
      type: 'Input',
      props: {
        maxlength: 200,
      },
    },
    {
      field: 'port',
      label: '端口',
      type: 'InputNumber',
      props: {
        max: 99999,
        min: 0,
      },
    },
    {
      field: 'dbName',
      label: '数据库名称',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'username',
      label: '用户名',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'password',
      label: '密码',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'initialSize',
      label: '初始化连接数',
      type: 'InputNumber',
      props: {
        max: 99999,
        min: 0,
      },
    },
    {
      field: 'minIdle',
      label: '最小连接数',
      type: 'InputNumber',
      props: {
        max: 99999,
        min: 0,
      },
    },
    {
      field: 'maxActive',
      label: '最大连接数',
      type: 'InputNumber',
      props: {
        max: 99999,
        min: 0,
      },
    },
  ]);

  const { required } = useValidator();

  const rules = reactive({
    name: [required()],
    host: [required()],
    port: [required()],
    dbName: [required()],
    username: [required()],
    password: [required()],
    initialSize: [required()],
    minIdle: [required()],
    maxActive: [required()],
  });

  const { formRegister, formMethods } = useForm();
  const { setValues, submitForm } = formMethods;

  const submit = async () => {
    return await submitForm();
  };

  watch(
    () => props.currentId,
    async (currentId) => {
      const res = await getApi(currentId);
      setValues(res);
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    submit,
  });
</script>
